package org.lwz.space.service;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public void start() throws Exception {
        ServerSocket ser = new ServerSocket(7776);
        while (true) {
            Socket socket = ser.accept();

            new Thread(new Client(socket)).start();
        }
    }


    public static void main(String[] args) throws Exception {
        new Server().start();

    }

}

class Client implements Runnable {
    private static String basePath = "E:\\lwz-zone\\lwz-zone\\src\\main\\resources";
    private Socket socket;

    public Client(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        PrintWriter writer = null;
        BufferedReader reader = null;
        BufferedReader freader = null;
        try {
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            writer = new PrintWriter(new OutputStreamWriter(out));

            reader = new BufferedReader(new InputStreamReader(in));

            String firstLine = reader.readLine();
            String url = firstLine.split(" ")[1];
            String path = basePath + url;
            freader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));

            writer.write("HTTP/1.1 500 OK\r\n");
            writer.write("Content-type:text/xml;charset=UTF-8\r\n");
            writer.write("\r\n");

            String s = "";
            while ((s = freader.readLine()) != null) {
                writer.print(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
            try {
                reader.close();
                freader.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}